package com.sea.demo.shiro.filter;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @Author: 快乐在角落里
 * @Create: 2020/11/8 12:27
 */
public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {

    private  final static Logger LOGGER = LogManager.getLogger(ShiroFormAuthenticationFilter.class);

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Login page view.");
                }
                //allow them to see the login page ;)
                return true;
            }
        } else {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Attempting to access a path which requires authentication.  Forwarding to the " +
                        "Authentication url [" + getLoginUrl() + "]");
            }
            WebUtils.issueRedirect(request, response, getLoginUrl(), null, true, false);
            return false;
        }
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return super.isAccessAllowed(request, response, mappedValue);
    }
}
